package org.video.mine.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.video.mine.GlobalStr;
import org.video.mine.MyPreference;
import org.video.mine.R;
import org.video.mine.Urls;
import org.video.mine.adapter.PlayListPlayAdapter;
import org.video.mine.databinding.ActivityPlayTestBinding;
import org.video.mine.entity.LoadedEntity;
import org.video.mine.entity.LoadingEntity;
import org.video.mine.entity.LookHistoryEntity;
import org.video.mine.entity.MoviePlayerEntity;
import org.video.mine.entity.PlayListEntity;
import org.video.mine.event.DownLoadAllEvent;
import org.video.mine.event.LoadFailedEvent;
import org.video.mine.event.RefreshHistoryEvent;
import org.video.mine.mycode.DownTask;
import org.video.mine.mycode.DownThread;
import org.video.mine.mycode.OrientationListener;
import org.video.mine.mycode.ShowMessageDialog;
import org.video.mine.mycode.SpeedPopWindow;
import org.video.mine.network.JsoupGet;
import org.video.mine.utils.DataUtils;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class PlayerActivity extends AppCompatActivity implements SurfaceHolder.Callback,
        IMediaPlayer.OnPreparedListener,
        IMediaPlayer.OnCompletionListener,
        IMediaPlayer.OnErrorListener,
        IMediaPlayer.OnInfoListener, View.OnClickListener,
        IMediaPlayer.OnSeekCompleteListener,
        IMediaPlayer.OnVideoSizeChangedListener,
        SeekBar.OnSeekBarChangeListener, View.OnTouchListener{

    //https://iqiyi.cdn9-okzy.com/20200806/13598_3a5997ca/1000k/hls/index.m3u8
    private ActivityPlayTestBinding binding;

    private IjkMediaPlayer mPlayer;
    private boolean isShow = false;
    public static final int UPDATE_TIME = 0x0001;
    public static final int HIDE_CONTROL = 0x0002;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case 0:
                    try {
                        if (mPlayer==null)
                            return;
                        Log.d("playerM3u8=",m3u8Url);
                        mPlayer.reset();
                        initPlayer();

                        mPlayer.setDisplay(binding.surfaceView.getHolder());
                        binding.pbLoading.setVisibility(View.VISIBLE);
                        mPlayer.setDataSource(m3u8Url);
                        mPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", 1);//设置倍速是否变声1 不变，0改变
                        mPlayer.prepareAsync();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                break;
                case UPDATE_TIME:
                    updateTime();
                    mHandler.sendEmptyMessageDelayed(UPDATE_TIME, 500);
                    break;
                case HIDE_CONTROL:
                    hideControl();
                    break;
                case 3:
                    if (binding.pbLoading==null)
                        return;
                    binding.pbLoading.setVisibility(View.GONE);
                    binding.playOrPause.setVisibility(View.INVISIBLE);
                    binding.tvError.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    if (binding.tvMovie==null)
                        return;
                    if (playLists!=null){
                        playListAdapter.notifyDataSetChanged();
                        binding.tvMovie.setText(name);
                        binding.movieName.setText(playLists.get(position).getPlayLists().get(which).getName());
                        LookHistoryEntity lookHistoryEntity = new LookHistoryEntity();
                        lookHistoryEntity.setName(name+"("+playLists.get(position).getPlayLists().get(which).getName()+")");
                        int pos = isHave(lookHistoryEntity);
                        if (pos>=0 && currentPosition==0){
                            haveLsatHistory = true;
                            currentPositionHistory = historyEntities.get(pos).getPlayPosition();
                            binding.tvShowMsg.setText("记忆您上次播放到"+DataUtils.timeToString(currentPositionHistory)+"，");
                        }
                    }
                    break;
                case 5:
                    saveHistory();
                    mHandler.sendEmptyMessageDelayed(5, 5000);
                    break;
                case 6:
                    if (binding.llLast==null)
                        return;
                    haveLsatHistory = false;
                    binding.llLast.setVisibility(View.GONE);
                    break;
                case 7:
                    Toast.makeText(context, (CharSequence) msg.obj,Toast.LENGTH_SHORT).show();
                    break;
                case 8:
                    if (binding.ivDown==null)
                        return;
                    binding.ivDown.setVisibility(View.GONE);
                    break;
                case 9:
                    if (binding.ivDown==null)
                        return;
                    binding.ivDown.setVisibility(View.VISIBLE);
                    break;
                case 10:
                    int pos = (int) msg.obj;
                    showMessageDialog(pos);
                    break;
            }
        }
    };
    private String m3u8Url="";
    private List<List> tsLists;
    private Context context;
    public int which = 0;
    private String imgUrl="";
    private MyPreference preference;
    private String name="";
    public boolean autoPlay = true;
    public int currentPosition=0;
    public int currentPositionHistory=0;
    public String homeUrl="";
    private PlayListPlayAdapter playListAdapter;
    private List<PlayListEntity> playLists = new ArrayList<>();
    public int position=0;
    public String url;
    private String tsHomeUrl;
    private boolean playDestroyed = false;
    private boolean surfaceDestroy = false;
    private boolean prepared = false;
    private boolean isPlaying = false;
    public boolean loaded = false;
    private boolean completioned = false;
    private boolean haveLsatHistory = false;
    private List<LookHistoryEntity> historyEntities;
    private LookHistoryEntity historyEntity;
    private List<LoadingEntity> loadingEntities;
    private boolean loadError = false;
    private int width=0;
    private int height = 0;

    private OrientationListener orientationListener;
    private AudioManager audioManager;
    private int maxVolume=0;
    private int minVolume=0;
    private int currentVolume=0;
    private long clickDown=0;
    private boolean surfaceCreated = false;
    private int changeProGress=0;
    private SpeedPopWindow speedPop;
    private float playSpeed=1.0f;
    private boolean isPause = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_play_test);
        setContentView(binding.getRoot());
        EventBus.getDefault().register(this);

        context = this;
        orientationListener = new OrientationListener(context,PlayerActivity.this);
        orientationListener.enable();
        checkScreenOrientation();

        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        initPlayer();
        initSruface();
        initView();
        initData();
    }


    private void initData() {
        Bundle bundle = getIntent().getBundleExtra("bundle");
//        playerEntities = (List<MoviePlayerEntity>) bundle.getSerializable("play");
        url = bundle.getString("url");
        homeUrl = url;
        which = bundle.getInt("which");
        position = bundle.getInt("position");
        imgUrl = bundle.getString("imgUrl");
        name = bundle.getString("name");
        currentPosition = bundle.getInt("time");

        audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if (Build.VERSION.SDK_INT>=28) {
            minVolume = audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC);
        }
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        binding.pbVolume.setMax(maxVolume);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            binding.pbVolume.setMin(minVolume);
        }
        binding.pbVolume.setProgress(currentVolume);
        if (currentVolume<=minVolume){
            binding.ivVoice.setImageResource(R.drawable.no_voice);
        }else {
            binding.ivVoice.setImageResource(R.drawable.voice);
        }

        preference = MyPreference.getInstance();
        preference.setPreference(context);
        loadingEntities = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadedEntity.class);
        if (loadingEntities==null){
            loadingEntities = new ArrayList<>();
        }

        if (!TextUtils.isEmpty(url)) {
            getNetData();
        }
    }

    public void getNetData(){
        if (binding.llLast==null)
            return;
        if (mPlayer!=null){
            mPlayer.setSpeed(1.0f);
        }
        isPause = false;
        binding.ivSp.setText("");
        binding.llLast.setVisibility(View.GONE);
        binding.rlSet.setVisibility(View.GONE);
        binding.controlLl.setVisibility(View.GONE);
        binding.rlTopName.setVisibility(View.GONE);
        playListAdapter.setPosition(position);
        playListAdapter.setWhich(which);
        binding.pbLoading.setVisibility(View.VISIBLE);
        binding.playOrPause.setVisibility(View.GONE);
        binding.tvError.setVisibility(View.GONE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String m3u8="";
                List<List> movieList = JsoupGet.getPanelBody(url);
                if (movieList.size()==3) {
                    playLists.clear();
                    m3u8 = (String) movieList.get(0).get(0);
                    playLists.addAll(movieList.get(1));
                    name = (String) movieList.get(2).get(0);
                }
                if (playLists!=null && playLists.size()>0) {
                    if (name.length()>10){
                        name = name.substring(0,10);
                    }else {
                        name = name;
                    }
                    if (mHandler!=null)
                    mHandler.sendEmptyMessage(4);
                }
                if (!TextUtils.isEmpty(m3u8)) {
                    File loadFile = new File(GlobalStr.getSDPath(context) + name + "/" + playLists.get(position).getPlayLists().get(which).getName() + GlobalStr.saveType);
                    if (loadFile.exists()) {
                        if (mHandler!=null)
                            mHandler.sendEmptyMessage(8);
                        m3u8Url = loadFile.getAbsolutePath();
                        if (mHandler!=null) {
                            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                            retriever.setDataSource(loadFile.getPath());
                            String hei = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
                            String wid = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
                            width = Integer.valueOf(wid)>Integer.valueOf(hei)?Integer.valueOf(wid):Integer.valueOf(hei);
                            height = Integer.valueOf(wid)<Integer.valueOf(hei)?Integer.valueOf(wid):Integer.valueOf(hei);
                            mHandler.sendEmptyMessage(0);
                        }
                    }else {
                        if (mHandler!=null)
                            mHandler.sendEmptyMessage(9);
                        String homeUrl = m3u8.substring(0, m3u8.lastIndexOf("/") + 1);
                        HashMap map = JsoupGet.getM3u8(m3u8);
                        String m3u81 = (String) map.get("m3u8");
                        if (map.size()>1){
                            String wh = (String) map.get("wh");
                            String[] xes = wh.split("x");
                            width = Integer.valueOf(xes[0])>Integer.valueOf(xes[1])?Integer.valueOf(xes[0]):Integer.valueOf(xes[1]);
                            height = Integer.valueOf(xes[0])<Integer.valueOf(xes[1])?Integer.valueOf(xes[0]):Integer.valueOf(xes[1]);
                        }
                        if (TextUtils.isEmpty(m3u81)) {
                            m3u8Url = m3u8;
                        } else {
                            String newHome = homeUrl.replace("//","/");
                            String[] homeSplite = newHome.split("/");
                            String[] m3u81Splites = m3u81.split("/");
                            List<String> homeLists = Arrays.asList(homeSplite);
                            if (m3u81Splites.length>1 && homeLists.contains(m3u81Splites[1])){
                                int tsIndex = homeLists.indexOf(m3u81Splites[1]);
                                m3u8Url = homeUrl.substring(0,homeUrl.indexOf(homeSplite[tsIndex])) + "/" + m3u81;
                            } else {
                                m3u8Url = homeUrl + m3u81;
                            }
                        }
                        tsHomeUrl = m3u8Url.substring(0, m3u8Url.lastIndexOf("/") + 1);
                        if (!TextUtils.isEmpty(m3u8Url) && m3u8Url.endsWith(".m3u8")) {
                            tsLists = JsoupGet.getTs(m3u8Url);
                            /*ijkhttphook:+m3u8Url//断网自动重新连接 url前接上ijkhttphook:
                            然后再调用((IjkMediaPlayer)mediaPlayer).setOnNativeInvokeListener(new IjkMediaPlayer.OnNativeInvokeListener() {

                                @Override

                                public boolean onNativeInvoke(int i, Bundle bundle) {

                                    return true;

                                }

                            })*/
                            if (mHandler!=null)
                            mHandler.sendEmptyMessage(0);
                        } else {
                            if (mHandler!=null)
                            mHandler.sendEmptyMessage(3);
                        }
                    }
                }else {
                    if (mHandler!=null)
                    mHandler.sendEmptyMessage(3);
                }
            }
        }).start();
    }

    private void initPlayer() {
        mPlayer = createPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setOnCompletionListener(this);

        mPlayer.setOnErrorListener(this);
        mPlayer.setOnInfoListener(this);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnSeekCompleteListener(this);
        mPlayer.setOnVideoSizeChangedListener(this);
        mPlayer.setDisplay(binding.surfaceView.getHolder());
    }

    public IjkMediaPlayer createPlayer() {
        IjkMediaPlayer ijkMediaPlayer = new IjkMediaPlayer();
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_CODEC, "skip_loop_filter", 48);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "protocol_whitelist", "crypto,file,http,https,tcp,tls,udp");

        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fflags", "fastseek");//设置seekTo能够快速seek到指定位置并播放
        //设置播放前的最大探测时间
//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT,"analyzemaxduration",100L);
        //设置播放前的探测时间 1,达到首屏秒开效果
//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT,"analyzeduration",1);
        //播放前的探测Size，默认是1M, 改小一点会出画面更快
//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT,"probesize",1024*10);
        //是否开启预缓冲，一般直播项目会开启，达到秒开的效果，不过带来了播放丢帧卡顿的体验
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER,"packet-buffering",1);
        //播放重连次数
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER,"reconnect",5);
        //跳帧处理,放CPU处理较慢时，进行跳帧处理，保证播放流程，画面和声音同步
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER,"framedrop",5);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER,"max-buffer-size",500*1024);
        //某些视频在SeekTo的时候，会跳回到拖动前的位置，这是因为视频的关键帧的问题，通俗一点就是FFMPEG不兼容，视频压缩过于厉害，seek只支持关键帧，出现这个情况就是原始的视频文件中i 帧比较少
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
        return ijkMediaPlayer;
    }
    public void stopPlay(){
        if (isPlaying) {
            isPlaying = false;
            mPlayer.stop();
        }
        mHandler.removeMessages(0);
        mHandler.removeMessages(UPDATE_TIME);
        mHandler.removeMessages(HIDE_CONTROL);
        mHandler.removeMessages(3);
        mHandler.removeMessages(4);
        mHandler.removeMessages(5);
        mHandler.removeMessages(6);
        mPlayer.reset();
    }

    private void initView() {
        speedPop = new SpeedPopWindow(context);
        speedPop.setSpeedClick(new SpeedPopWindow.SpeedClick() {
            @Override
            public void speed(float speed) {
                if (mPlayer!=null){
                    mPlayer.setSpeed(speed);
                }
                playSpeed = speed;
                if (speed==1.0f){
                    binding.ivSp.setText("");
                }else {
                    binding.ivSp.setText("x"+speed);
                }
                speedPop.dismissPopWindow();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rlList.setLayoutManager(layoutManager);
        playListAdapter = new PlayListPlayAdapter(playLists,context,this);
        binding.rlList.setAdapter(playListAdapter);

        binding.ivRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer.isPlaying()){
                    currentPosition = (int) mPlayer.getCurrentPosition();
                }
                mPlayer.stop();
                isPlaying = false;
                autoPlay = true;
                binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
                binding.playOrPause.setImageResource(R.drawable.play);
                binding.pbLoading.setVisibility(View.VISIBLE);
                binding.playOrPause.setVisibility(View.INVISIBLE);
                getNetData();
            }
        });
        binding.tvSpeed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (speedPop == null) {
                    speedPop = new SpeedPopWindow(context);
                }
                speedPop.show(binding.ivSp);
                hideControl();
            }
        });

        binding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        binding.tvError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayer.reset();
                loadError = false;
                binding.pbLoading.setVisibility(View.VISIBLE);
                binding.playOrPause.setVisibility(View.INVISIBLE);
                binding.tvError.setVisibility(View.GONE);
                getNetData();
            }
        });
        binding.ivScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    orientationListener.orientationPortraitLocked = true;
                    orientationListener.orientationLandscapeLocked = false;
                }else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    orientationListener.orientationPortraitLocked = false;
                    orientationListener.orientationLandscapeLocked = true;
                }
            }
        });
        binding.ivPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                play();
            }
        });
        binding.tvShowMsgTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer!=null){
                    binding.pbLoading.setVisibility(View.VISIBLE);
                    binding.llLast.setVisibility(View.GONE);
                    if (currentPositionHistory>5000){
                        currentPositionHistory = currentPositionHistory-5000;
                    }else {
                        currentPositionHistory = 0;
                    }
                    mPlayer.seekTo(currentPositionHistory);
                    if (!isPlaying){
                        play();
                    }
                }
            }
        });

        binding.ivDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File saveFile1 = new File(GlobalStr.getSDPath(context), name + "/" + playLists.get(position).getPlayLists().get(which).getName() + GlobalStr.saveType);
                if (saveFile1.exists()){
                    Message message = Message.obtain();
                    message.what = 7;
                    message.obj = name + playLists.get(position).getPlayLists().get(which).getName()+"  已下载";
                    mHandler.sendMessage(message);
                }else {
                    if (DownTask.downThreadList == null) {
                        DownTask.downThreadList = new ArrayList<>();
                    }
                    boolean isHave = false;
                    DownThread downThread = null;
                    for (DownThread thread : DownTask.downThreadList) {
                        if (thread.name.equals(name) && thread.set.equals(playLists.get(position).getPlayLists().get(which).getName())) {
                            isHave = true;
                            downThread = thread;
                            break;
                        }
                    }
                    if (!isHave) {
                        loadingEntities = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadingEntity.class);
                        if (loadingEntities == null) {
                            loadingEntities = new ArrayList<>();
                        }
                        LoadingEntity loadingEntity = new LoadingEntity();
                        loadingEntity.setImgUrl(imgUrl);
                        loadingEntity.setName(GlobalStr.returnName(name));
                        if (tsLists.size() > 0) {
                            loadingEntity.setAllCount(tsLists.get(1).size());
                        }
                        loadingEntity.setSet(playLists.get(position).getPlayLists().get(which).getName());
                        loadingEntity.setUrl(m3u8Url);
                        loadingEntities.add(loadingEntity);
                        preference.setObject(MyPreference.loading, loadingEntities);
                        DownThread thread = new DownThread(m3u8Url, name, playLists.get(position).getPlayLists().get(which).getName(), context, imgUrl);
//                    thread.start();
                        int pos = DownTask.downThreadList.size();
                        DownTask.downThreadList.add(pos, thread);
                        DownTask.startDown(pos);
                    } else {
                        if (!downThread.isStarted) {
//                        downThread.start();
                            int i = DownTask.downThreadList.indexOf(downThread);
                            DownTask.startDown(i);
                        }
                    }
                    Message message = Message.obtain();
                    message.what = 7;
                    message.obj = "开始下载 " + name + playLists.get(position).getPlayLists().get(which).getName();
                    mHandler.sendMessage(message);
                }
            }
        });

        binding.playOrPause.setOnClickListener(this);
        binding.rootRl.setOnClickListener(this);
        binding.rootRl.setOnTouchListener(this);
        binding.controlLl.setOnTouchListener(this);
        binding.tvForward.setOnClickListener(this);
        binding.tvBackward.setOnClickListener(this);
        binding.ivLast.setOnClickListener(this);
        binding.ivLastSet.setOnClickListener(this);
        binding.ivNext.setOnClickListener(this);
        binding.ivNextSet.setOnClickListener(this);
        binding.tvProgess.setOnSeekBarChangeListener(this);
        binding.surfaceView.setOnTouchListener(this);
    }

    private void initSruface(){
        binding.surfaceView.setZOrderOnTop(false);
        binding.surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        binding.surfaceView.getHolder().addCallback(this);
    }

    private void play() {
        if (mPlayer == null) {
            return;
        }
        autoPlay = false;
        binding.rlSet.setVisibility(View.GONE);
        if (loaded) {
            if (isPlaying) {
                mPlayer.pause();
                currentPosition = (int) mPlayer.getCurrentPosition();
                binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
                isPlaying = false;
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                mHandler.removeMessages(UPDATE_TIME);
                mHandler.removeMessages(HIDE_CONTROL);
                mHandler.removeMessages(5);
                binding.playOrPause.setVisibility(View.VISIBLE);
                isPause = true;
                binding.playOrPause.setImageResource(R.drawable.play);
            } else {
                mPlayer.start();
                binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_pause);
                completioned = false;
                isPlaying = true;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                mHandler.sendEmptyMessageDelayed(UPDATE_TIME, 500);
                mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
                mHandler.sendEmptyMessage(5);
                binding.playOrPause.setVisibility(View.INVISIBLE);
                isPause = false;
                binding.playOrPause.setImageResource(R.drawable.play_pause);
                if (historyEntity == null) {
                    historyEntity = new LookHistoryEntity();
                }
                historyEntity.setImgUrl(imgUrl);
                historyEntity.setName(name + "(" + playLists.get(position).getPlayLists().get(which).getName() + ")");
                historyEntity.setPlayPosition(0);
                historyEntity.setPlayUrl(homeUrl);
                historyEntity.setAllTimes((int) mPlayer.getDuration());
            }
        }
    }

    private void checkScreenOrientation(){
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_PORTRAIT){
            binding.llPlay.setVisibility(View.VISIBLE);
            binding.ivScreen.setImageResource(R.drawable.full_screen);
            //当前为竖屏， 在此处添加额外的处理代码
            System.out.println("-----------------onConfigurationChanged--------->:2");
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;
            int height = dm.heightPixels;
            ViewGroup.LayoutParams lp = binding.surfaceView.getLayoutParams();
            lp.width = width;
            lp.height = (int) (height * (1 - 0.618));
            binding.surfaceView.setLayoutParams(lp);
            getWindow().getDecorView().setSystemUiVisibility(View.VISIBLE);//显示状态
        }else {
            binding.llPlay.setVisibility(View.GONE);
            binding.ivScreen.setImageResource(R.drawable.half_screen);
            getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);//消除状态栏
            System.out.println("-----------------onConfigurationChanged--------->:1");
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;
            int height = dm.heightPixels;
            ViewGroup.LayoutParams lp = binding.surfaceView.getLayoutParams();
            lp.width = width;
            lp.height = height;
            binding.surfaceView.setLayoutParams(lp);
        }
    }

    long backTime = 0;
    @Override
    public void onBackPressed() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            if (System.currentTimeMillis() - backTime < 1000) {
                saveHistory();
                PlayerActivity.this.finish();
            } else {
                Toast.makeText(context, "再按一次退出播放", Toast.LENGTH_SHORT).show();
                backTime = System.currentTimeMillis();
            }
        }
    }

    private int isHave(LookHistoryEntity historyEntity){
        int isHave = -1;
        historyEntities = (List<LookHistoryEntity>) preference.getObject(MyPreference.history,LookHistoryEntity.class);
        if (historyEntities==null){
            historyEntities = new ArrayList<>();
        }
        if (historyEntity==null)
            return -2;
        for (int i=0;i<historyEntities.size();i++){
            LookHistoryEntity item = historyEntities.get(i);
            if (item.getName().equals(historyEntity.getName())){
                isHave = i;
                break;
            }
        }
        return isHave;
    }

    public void saveHistory(){
        if (loaded && mPlayer.getCurrentPosition()>0){
            if (historyEntity!=null){
                int have = isHave(historyEntity);
                if (have==-2)
                    return;
                if (have!=-1) {
                    historyEntities.remove(have);
                }
                historyEntity.setLoaded(false);
                historyEntity.setWhich(which);
                historyEntity.setPosition(position);
                historyEntity.setPlayPosition((int) mPlayer.getCurrentPosition());
                historyEntities.add(historyEntity);
                preference.setObject(MyPreference.history,historyEntities);
                EventBus.getDefault().post(new RefreshHistoryEvent());
            }
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){//横屏
            binding.llPlay.setVisibility(View.GONE);
            binding.ivScreen.setImageResource(R.drawable.half_screen);
            getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);//消除状态栏
            System.out.println("-----------------onConfigurationChanged--------->:1");
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width1 = dm.widthPixels;
            int height1 = dm.heightPixels;

            if (width>0 && height>0) {
                double w = ((float) width1) / width;
                double h = ((float) height1) / height;
                if (w > h) {
                    width1 = (int) (width * h);
                } else {
                    height1 = (int) (height * w);
                }
            }

            ViewGroup.LayoutParams lp = binding.surfaceView.getLayoutParams();
            lp.width = width1;
            lp.height = height1;
            binding.surfaceView.setLayoutParams(lp);
        }else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){//竖屏
            binding.llPlay.setVisibility(View.VISIBLE);
            binding.ivScreen.setImageResource(R.drawable.full_screen);
            //当前为竖屏， 在此处添加额外的处理代码
            System.out.println("-----------------onConfigurationChanged--------->:2");
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width1 = dm.widthPixels;
            int height1 = (int) (dm.heightPixels * 0.28);

            if (width>0 && height>0) {
                double w = ((float) width1) / width;
                double h = ((float) height1) / height;
                if (w > h) {
                    width1 = (int) (width * h);
                } else {
                    height1 = (int) (height * w);
                }
            }

            ViewGroup.LayoutParams lp = binding.surfaceView.getLayoutParams();
            lp.width = width1;
            lp.height = height1;
            binding.surfaceView.setLayoutParams(lp);
            getWindow().getDecorView().setSystemUiVisibility(View.VISIBLE);//显示状态
        }
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {
        Log.d("suffactStatue","completion");
        currentPosition = (int) mPlayer.getCurrentPosition();
        if (currentPosition+5000<mPlayer.getDuration()){
            completioned = false;
            isPlaying = false;
            mPlayer.seekTo(currentPosition);
            play();
            return;
        }
        if (loadError)
            return;
        completioned = true;
        saveHistory();
        updateTime();
        currentPosition = 0;
        mHandler.removeMessages(UPDATE_TIME);
        mHandler.removeMessages(HIDE_CONTROL);
        mHandler.removeMessages(5);
        binding.rlSet.setVisibility(View.VISIBLE);
        binding.controlLl.animate().setDuration(300).translationY(0);
        binding.rlTopName.animate().setDuration(300).translationY(0);
        isPlaying = false;
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        binding.playOrPause.setImageResource(R.drawable.play);
        binding.playOrPause.setVisibility(View.VISIBLE);
        binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {
        Log.d("suffactStatue","error"+what);
        autoPlay = true;
        binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
        binding.playOrPause.setImageResource(R.drawable.play);
        binding.pbLoading.setVisibility(View.GONE);
        binding.tvError.setVisibility(View.VISIBLE);
        isPlaying = false;
        loadError = true;
        mPlayer.stop();
        mPlayer.reset();
        return false;
    }

    @Override
    public boolean onInfo(IMediaPlayer mp, int what, int extra) {
        Log.d("suffactStatue","info"+what);
        if (what==MediaPlayer.MEDIA_INFO_BUFFERING_START){
            if (binding.playOrPause.getVisibility()==View.VISIBLE) {
                isPause = true;
                binding.playOrPause.setVisibility(View.INVISIBLE);
            }
            binding.pbLoading.setVisibility(View.VISIBLE);
        }else if(what==MediaPlayer.MEDIA_INFO_BUFFERING_END){
            binding.pbLoading.setVisibility(View.GONE);
            if (isPause){
                binding.playOrPause.setVisibility(View.VISIBLE);
            }
        }
        return false;
    }

    @Override
    public void onPrepared(IMediaPlayer mp) {
        Log.d("suffactStatue","width="+width+",height="+height);
        completioned = false;
        loaded = true;
        binding.controlLl.setVisibility(View.VISIBLE);
        binding.rlTopName.setVisibility(View.VISIBLE);
        isShow = true;
        mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
        binding.pbLoading.setVisibility(View.GONE);
        binding.tvError.setVisibility(View.GONE);
        prepared = true;
        setSize();
        if (currentPosition>5000){
            currentPosition = currentPosition-5000;
        }else {
            currentPosition = 0;
        }
        if (!autoPlay && currentPosition==0) {
            binding.playOrPause.setVisibility(View.VISIBLE);
        }else {
            if (currentPosition!=0) {
                binding.pbLoading.setVisibility(View.VISIBLE);
                mPlayer.seekTo(currentPosition);
            }
            binding.playOrPause.setVisibility(View.INVISIBLE);
            play();
        }
        if (haveLsatHistory){
            binding.llLast.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(6, 5000);
        }
        binding.tvStartTime.setText(DataUtils.timeToString(mp.getCurrentPosition()));
        binding.tvEndTime.setText(DataUtils.timeToString(mp.getDuration()));
        binding.tvProgess.setMax((int) mp.getDuration());
        binding.tvProgess.setProgress((int) mp.getCurrentPosition());
    }

    private void setSize(){
        Configuration newConfig = getResources().getConfiguration();
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){//横屏
            binding.llPlay.setVisibility(View.GONE);
            binding.ivScreen.setImageResource(R.drawable.half_screen);
            getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);//消除状态栏
            System.out.println("-----------------onConfigurationChanged--------->:1");
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width1 = dm.widthPixels;
            int height1 = dm.heightPixels;

            if (width>0 && height>0) {
                double w = ((float) width1) / width;
                double h = ((float) height1) / height;
                if (w > h) {
                    width1 = (int) (width * h);
                } else {
                    height1 = (int) (height * w);
                }
            }


            ViewGroup.LayoutParams lp = binding.surfaceView.getLayoutParams();
            lp.width = width1;
            lp.height = height1;
            binding.surfaceView.setLayoutParams(lp);
        }else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){//竖屏
            binding.llPlay.setVisibility(View.VISIBLE);
            binding.ivScreen.setImageResource(R.drawable.full_screen);
            //当前为竖屏， 在此处添加额外的处理代码
            System.out.println("-----------------onConfigurationChanged--------->:2");
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width1 = dm.widthPixels;
            int height1 = (int) (dm.heightPixels * 0.28);

            if (width>0 && height>0) {
                double w = ((float) width1) / width;
                double h = ((float) height1) / height;
                if (w > h) {
                    width1 = (int) (width * h);
                } else {
                    height1 = (int) (height * w);
                }
            }

            ViewGroup.LayoutParams lp = binding.surfaceView.getLayoutParams();
            lp.width = width1;
            lp.height = height1;
            binding.surfaceView.setLayoutParams(lp);
            getWindow().getDecorView().setSystemUiVisibility(View.VISIBLE);//显示状态
        }
    }

    @Override
    public void onSeekComplete(IMediaPlayer mp) {
//        binding.pbLoading.setVisibility(View.GONE);
        Log.d("suffactStatue","seekComplete");
    }

    @Override
    public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sar_num, int sar_den) {
        Log.d("suffactStatue","videoSizeChange");
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d("suffactStatue","create");
        surfaceCreated = true;
        if (prepared){
            /*if (currentPosition>5000) {
                mPlayer.seekTo(currentPosition - 5000);
            }else {
                mPlayer.seekTo(0);
            }*/
            binding.pbLoading.setVisibility(View.GONE);
            playDestroyed = false;
            mPlayer.setDisplay(holder);
            surfaceDestroy = false;
            if (isPlaying){
                mPlayer.start();
            }else {
                binding.playOrPause.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d("suffactStatue","changed");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d("suffactStatue","destroy");
        surfaceCreated = false;
        surfaceDestroy = true;
        playDestroyed = true;
        mPlayer.setDisplay(null);
        mPlayer.pause();
        currentPosition = (int) mPlayer.getCurrentPosition();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_backward:
                mHandler.removeMessages(HIDE_CONTROL);
                backWard();
                mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
                break;
            case R.id.tv_forward:
                mHandler.removeMessages(HIDE_CONTROL);
                forWard();
                mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
                break;
            case R.id.playOrPause:
                play();
                break;
            case R.id.root_rl:
                showControl();
                break;
            case R.id.iv_last_set:
            case R.id.iv_last:
                which--;
                if (which>=0){
                    if (isPlaying){
                        mHandler.removeMessages(5);
                        mPlayer.pause();
                        binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
                        isPlaying = false;
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                        mHandler.removeMessages(UPDATE_TIME);
                        mHandler.removeMessages(HIDE_CONTROL);
                    }
                    currentPosition = 0;
                    autoPlay = true;
                    url = Urls.getHomeUrl0() + playLists.get(position).getPlayLists().get(which).getUrl();
                    homeUrl = url;
                    getNetData();
                }else {
                    which++;
                    Toast.makeText(context,"没有上一集了",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_next:
            case R.id.iv_next_set:
                which++;
                if (which<playLists.get(position).getPlayLists().size()){
                    if (isPlaying){
                        mHandler.removeMessages(5);
                        mPlayer.pause();
                        binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
                        isPlaying = false;
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                        mHandler.removeMessages(UPDATE_TIME);
                        mHandler.removeMessages(HIDE_CONTROL);
                    }
                    currentPosition = 0;
                    autoPlay = true;
                    url = Urls.getHomeUrl0() + playLists.get(position).getPlayLists().get(which).getUrl();
                    homeUrl = url;
                    getNetData();
                }else {
                    which--;
                    Toast.makeText(context,"没有下一集了",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 更新播放时间
     */
    private void updateTime() {
        if (binding.tvStartTime==null)
            return;
        binding.tvStartTime.setText(DataUtils.timeToString(
                mPlayer.getCurrentPosition()));
        binding.tvProgess.setProgress((int) mPlayer.getCurrentPosition());
    }

    /**
     * 隐藏进度条
     */
    private void hideControl() {
        if (binding.controlLl==null)
            return;
        isShow = false;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);//消除状态栏
        }
        mHandler.removeMessages(UPDATE_TIME);
        binding.controlLl.animate().setDuration(300).translationY(binding.controlLl.getHeight());
        binding.rlTopName.animate().setDuration(300).translationY(-binding.rlTopName.getHeight());
    }

    /**
     * 显示进度条
     */
    private long clickTime = 0;
    private void showControl() {

        if (speedPop.isShowing()){
            speedPop.dismissPopWindow();
            return;
        }

        if (!isShow) {
            isShow = true;
            mHandler.removeMessages(HIDE_CONTROL);
            mHandler.sendEmptyMessage(UPDATE_TIME);
            mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
            binding.controlLl.animate().setDuration(300).translationY(0);
            binding.rlTopName.animate().setDuration(300).translationY(0);
        }else {
            hideControl();
        }
        if (binding.pbLoading.getVisibility()!=View.VISIBLE && System.currentTimeMillis()-clickTime<400 && binding.pbLoading.getVisibility()!=View.VISIBLE){
            play();
        }
        clickTime = System.currentTimeMillis();
    }

    /**
     * 设置快进10秒方法
     */
    private void forWard(){
        if(mPlayer != null){
            int position = (int) mPlayer.getCurrentPosition();
            binding.pbLoading.setVisibility(View.VISIBLE);
            mPlayer.seekTo(position + 10000);
        }
    }

    /**

     * 设置快退10秒的方法

     */

    public void backWard(){
        if(mPlayer != null){
            int position;
            if (completioned){
                position = (int) mPlayer.getDuration();
            }else {
                position = (int) mPlayer.getCurrentPosition();
            }
            if(position > 10000){
                position-=10000;
            }else{
                position = 0;
            }
            binding.rlSet.setVisibility(View.GONE);
            binding.pbLoading.setVisibility(View.VISIBLE);
            mPlayer.seekTo(position);
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Log.d("progressStatue","ProgressChanged,progress="+progress);
        if(mPlayer != null && fromUser){
            changeProGress = progress;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mHandler.removeMessages(HIDE_CONTROL);
        Log.d("progressStatue","StartTrackingTouch");
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        Log.d("progressStatue","StopTrackingTouch");
        if (changeProGress<mPlayer.getDuration()){
            binding.rlSet.setVisibility(View.GONE);
        }
        mPlayer.seekTo(changeProGress);
        mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
    }

    private float y=0;
    private float x=0;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()){
            case R.id.control_ll:
                Log.d("controlTouch","true");
                mHandler.removeMessages(HIDE_CONTROL);
                mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
                return true;
            case R.id.surfaceView:
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        clickDown = System.currentTimeMillis();
                        y=event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float changeY = event.getY()-y;
                        y = event.getY();
                        if (Math.abs(changeY)>5) {
                            currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                            binding.llVoice.setVisibility(View.VISIBLE);
                            if (changeY < 0) {
                                currentVolume++;
                                if (currentVolume <= maxVolume) {
                                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_PLAY_SOUND);
                                } else {
                                    currentVolume--;
                                }
                            } else {
                                currentVolume--;
                                if (currentVolume >= minVolume) {
                                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_PLAY_SOUND);
                                } else {
                                    currentVolume++;
                                }
                            }
                            if (currentVolume<=minVolume){
                                binding.ivVoice.setImageResource(R.drawable.no_voice);
                            }else {
                                binding.ivVoice.setImageResource(R.drawable.voice);
                            }
                            binding.pbVolume.setProgress(currentVolume);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (System.currentTimeMillis() - clickDown < 400) {
                            showControl();
                        }
                        binding.llVoice.setVisibility(View.GONE);
                        break;
                }
                return true;
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayer!=null && isPlaying) {
            currentPosition = (int) mPlayer.getCurrentPosition();
            mPlayer.pause();
        }
        if (mPlayer.getCurrentPosition()!=0){
            saveHistory();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (playDestroyed && prepared) {
            binding.playOrPause.setVisibility(View.GONE);
            binding.pbLoading.setVisibility(View.VISIBLE);
        }else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (prepared && !surfaceDestroy && surfaceCreated) {
                        isPlaying = true;
                        mPlayer.start();
                    }
                }
            },10);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!surfaceCreated){
            initSruface();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(UPDATE_TIME);
        mHandler.removeMessages(HIDE_CONTROL);
        mHandler.removeMessages(5);
        mHandler.removeMessages(6);
        mHandler.removeMessages(0);
        mHandler.removeMessages(3);
        mHandler.removeMessages(4);
        orientationListener.disable();
        binding.surfaceView.getHolder().removeCallback(this);
        release();
        EventBus.getDefault().unregister(this);
    }

    private void release() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
        IjkMediaPlayer.native_profileEnd();
    }

    @Subscribe
    public void loadEvent(final DownLoadAllEvent event){
        if (event!=null){
            Message message = Message.obtain();
            message.what = 10;
            message.obj = event.pos;
            mHandler.sendMessage(message);
        }
    }

    @Subscribe
    public void loadFailed(LoadFailedEvent event){
        if (event!=null){
            Message message = Message.obtain();
            message.what = 7;
            message.obj = event.msg;
            mHandler.sendMessage(message);
//            Toast.makeText(context, event.msg,Toast.LENGTH_SHORT).show();
        }
    }

    private void showMessageDialog(final int pos){
        final ShowMessageDialog dialog = new ShowMessageDialog(context,true);
        dialog.setTvTitle("请选择下载内容");
        dialog.setRecyView(PlayerActivity.this.playLists.get(pos).getPlayLists());
//        dialog.setTvContent("是否下载《"+name+"》全集？");
        dialog.setClickListener(new ShowMessageDialog.ClickListener() {
            @Override
            public void clickPositive(final List<MoviePlayerEntity> playListsLoad) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i=0;i<playListsLoad.size();i++){
                            MoviePlayerEntity moviePlayerEntity = playListsLoad.get(i);
                            if (DownTask.downThreadList == null) {
                                DownTask.downThreadList = new ArrayList<>();
                            }
                            boolean isHave = false;
                            DownThread downThread = null;
                            for (DownThread thread : DownTask.downThreadList) {
                                if (thread.name.equals(name) && thread.set.equals(moviePlayerEntity.getName())) {
                                    isHave = true;
                                    downThread = thread;
                                    break;
                                }
                            }
                            File loadFile = new File(GlobalStr.getSDPath(context) + name + "/" + moviePlayerEntity.getName() + GlobalStr.saveType);
                            if (!isHave && !loadFile.exists()){
                                String m3u8="";
                                String m3u8Url="";
                                String name="";
                                String url = moviePlayerEntity.getUrl().startsWith("http")?moviePlayerEntity.getUrl():(Urls.getHomeUrl0() + moviePlayerEntity.getUrl());
                                List<List> movieList = JsoupGet.getPanelBody(url);
                                if (movieList.size()==3) {
                                    m3u8 = (String) movieList.get(0).get(0);
                                    name = (String) movieList.get(2).get(0);
                                }
                                if (name.length()>10){
                                    name = name.substring(0,10);
                                }
                                if (!TextUtils.isEmpty(m3u8)) {
                                    String homeUrl = m3u8.substring(0, m3u8.lastIndexOf("/") + 1);
                                    String m3u81 = JsoupGet.getM3u8(m3u8).get("m3u8");;
                                    if (TextUtils.isEmpty(m3u81)) {
                                        m3u8Url = m3u8;
                                    } else {
                                        String[] homeSplite = homeUrl.split("/");
                                        String[] m3u81Splites = m3u81.split("/");
                                        if (m3u81Splites[1].equals(homeSplite[3])) {
                                            m3u8Url = homeSplite[0] + "//" + homeSplite[2] + "/" + m3u81;
                                        } else {
                                            m3u8Url = homeUrl + m3u81;
                                        }
                                    }
                                    if (!TextUtils.isEmpty(m3u8Url) && m3u8Url.endsWith(".m3u8")) {
                                        List<List> tsLists = JsoupGet.getTs(m3u8Url);
                                        List<LoadingEntity> loadingEntities = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadingEntity.class);
                                        if (loadingEntities == null) {
                                            loadingEntities = new ArrayList<>();
                                        }
                                        LoadingEntity loadingEntity = new LoadingEntity();
                                        loadingEntity.setImgUrl(imgUrl);
                                        loadingEntity.setName(GlobalStr.returnName(name));
                                        if (tsLists.size() > 0) {
                                            loadingEntity.setAllCount(tsLists.get(1).size());
                                        }else {
                                            loadingEntity.setAllCount(0);
                                            EventBus.getDefault().post(new LoadFailedEvent(name + moviePlayerEntity.getName()+" 下载失败！"));
                                            return;
                                        }
                                        loadingEntity.setSet(moviePlayerEntity.getName());
                                        loadingEntity.setUrl(m3u8Url);
                                        loadingEntities.add(loadingEntity);
                                        preference.setObject(MyPreference.loading, loadingEntities);
                                        DownThread thread = new DownThread(m3u8Url, name, moviePlayerEntity.getName(), context, imgUrl);
                                        int pos = DownTask.downThreadList.size();
                                        DownTask.downThreadList.add(pos, thread);
                                        DownTask.startDown(pos);

                                        EventBus.getDefault().post(new LoadFailedEvent("开始下载 " + name + moviePlayerEntity.getName()));
                                    }
                                }
                            }else if (isHave){
                                if (!downThread.isLoading) {
                                    int m = DownTask.downThreadList.indexOf(downThread);
                                    DownTask.startDown(m);
                                    EventBus.getDefault().post(new LoadFailedEvent("开始下载 " + name + moviePlayerEntity.getName()));
                                }else {
                                    EventBus.getDefault().post(new LoadFailedEvent("正在下载 " + name + moviePlayerEntity.getName()));
                                }
                            }else if (loadFile.exists()){
                                EventBus.getDefault().post(new LoadFailedEvent(name + moviePlayerEntity.getName()+"  已下载"));
                            }
                        }

                    }
                }).start();
                dialog.dismiss();
            }

            @Override
            public void clickCancel() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

}
